package com.gqz.aircraftwar.mvp.model

import android.graphics.*
import com.gqz.aircraftwar.App
import com.gqz.aircraftwar.App.Companion.paint
import com.gqz.aircraftwar.R
import com.gqz.aircraftwar.util.BmpCache
import com.gqz.aircraftwar.util.d
import com.gqz.aircraftwar.util.i
import kotlinx.coroutines.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import kotlin.system.measureTimeMillis

/**
 * 地图背景类
 *
 * @author gqz
 * @data 2020/3/24
 */
class GameMap private constructor() {
    val TAG: String = "GameMap-->"

    var speed = 5
    var bg: Bitmap

    private object Holder {
        val instance = GameMap()
        const val delay = 1000L / 30L
    }

    companion object {
        var instance = Holder.instance
    }

    val ctx = newSingleThreadContext("Map")
    var job: Job? = null
    var maps = mutableListOf<Int>()

    init {
        bg = BmpCache.loadBmp(R.drawable.bg)
        var w = App.surfaceW
        var h = App.surfaceW.toFloat() / bg.width.toFloat() * bg.height.toFloat()
        bg = Bitmap.createScaledBitmap(bg, w, h.toInt(), false)
        var bmpH = bg.height
        maps.add(0)
        maps.add(bmpH)
        maps.add(bmpH * 2)

    }

    fun start() {
        job = GlobalScope.launch(ctx) {
            i(TAG, "start--> map worked in ${Thread.currentThread().name}")
            if (bg.isRecycled) {
                bg = BmpCache.loadBmp(R.drawable.bg)
                var w = App.surfaceW
                var h = App.surfaceW.toFloat() / bg.width.toFloat() * bg.height.toFloat()
                bg = Bitmap.createScaledBitmap(bg, w, h.toInt(), false)
            }
            while (App.isRunning) {
//                d(TAG, "running-->")
                loop()
                Thread.sleep(Holder.delay)
            }
        }
    }

    fun reset() {
        job?.cancel()
        maps.clear()
        maps.add(0)
        maps.add(bg.height)
        maps.add(bg.height * 2)
    }

    fun loop() {
        for (i in 0 until maps.size) {
            maps[i] = maps[i] - speed
        }
        var y = maps[0]
        if (y <= 0 - bg.height) {
            maps.removeAt(0)
            y = maps[1] + bg.height
            maps.add(y)
        }
    }

    inline fun draw(canvas: Canvas) {
        for (y in maps) {
            if (y <= App.surfaceH) {
                canvas.drawBitmap(bg, 0f, y.toFloat(), paint)
            }
        }
    }
}


